<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\model\PolicyRelation;
use think\Db;
use think\Exception;

/**
 * 库存变更记录
 *
 * @icon fa fa-circle-o
 */
class CompanyStocksConfirm extends Backend
{

    /**
     * CompanyStocksLog模型对象
     * @var \app\common\model\CompanyStocksConfirm
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\CompanyStocksConfirm;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("confirmTypeList", $this->model->getConfirmTypeList());
        $this->assignconfig("isSuper",$this->auth->isSuperAdmin() ? true :false);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $query = $this->model
                    ->with(['company','product']);

            if(!$this->auth->isSuperAdmin()){
                $company = $this->auth->getCompany();
                $query->where("company_id","=",$company->id);
            }
            $list = $query->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','type','before','changes','after','creator','confirm_type','create_time']);
                $row->visible(['company']);
				$row->getRelation('company')->visible(['name']);
				$row->visible(['product']);
				$row->getRelation('product')->visible(['name']);
            }
            $company = $this->auth->getCompany();

            $extend = [];
            if($this->auth->isSuperAdmin()){
                $data = Lib::getAdminCompanyStocks();
                foreach ($data as $key => $val){
                    $extend[] = [
                        "name" => $val['name'],
                        "value" => $val['stocks']
                    ];
                }
            }else{
                $stocks = Lib::getStocksByCompany($company->id);
                $extend[] = [
                    "name" => "库存",
                    "value" => $stocks ? $stocks->stocks : 0
                ];
            }

            $result = array("total" => $list->total(), "rows" => $list->items(),"extend" => $extend);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function record(){
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');

            if($params['type'] == 1){
                if($params['file_url'] == "" || !Tools::isFileExist($params['file_url'])){
                    $this->error(__('文件未上传！'));
                }
                $fileData = Tools::importExcel($params['file_url']);
                $changes = count($fileData) - 1;
            }elseif ($params['type'] == 2){
                $changes = 1;
            }

            $log = new \app\common\model\CompanyStocksConfirm();
            $log->company_id = $params['company_id'];
            $log->product_id = $params['product_id'];
            $log->policy_id = 0;
            $log->type = 1;
            $log->changes = $changes;
            $log->creator = $this->auth->id;
            $log->remark_content = $params['remark'] ? $params['remark'] : "设备入库";
            $log->add_type = $params['type'];
            $log->file_url = $params['file_url'];
            $log->file_url = $params['file_url'];
            $log->sn = $params['sn'];
            $result = $log->save();
            if($result){
                $this->success("录入成功，等待接收！");
            }else{
                $this->error("录入失败!");
            }
        }
        return $this->view->fetch();
    }

    public function check($ids){
        $row = $this->model->get($ids);

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $confirmType = $this->request->post('confirm_type');
        $confirmContent = $this->request->post('confirm_content');

        if($confirmType == 1){
            $data = [];
            $equipData = [];
            if($row->add_type == 1){
                $fileData = Tools::importExcel($row->file_url);
                for($i = 1;$i < count($fileData);$i++){
                    $sn = trim($fileData[$i][0]);
                    $equip = Lib::getEquip($sn);
                    if($equip){
                        $this->error("设备：{$sn}已入库！");
                    }
                    $data[] = [
                        "confirm_id" => $row->id,
                        "sn" => $sn
                    ];
                    $equipData[] = [
                        "sn" => $sn,
                        "top_id" => $row->company_id,
                        "main_type" => 1,
                        "main_id" => $row->company_id,
                        "product_id" => $row->product_id,
                        "policy_id" => $row->policy_id,
                        "status" => 0
                    ];
                }
            }elseif ($row->add_type == 2){
                $equip = Lib::getEquip($row->sn);
                if($equip){
                    $this->error("设备：{$row->sn}已入库！");
                }
                $data[] = [
                    "confirm_id" => $row->id,
                    "sn" => $row->sn
                ];
                $equipData[] = [
                    "sn" => $row->sn,
                    "top_id" => $row->company_id,
                    "main_type" => 1,
                    "main_id" => $row->company_id,
                    "product_id" => $row->product_id,
                    "policy_id" => $row->policy_id,
                    "status" => 0
                ];
            }

            Db::startTrans();
            try {
                $row->confirm_type = 1;
                $row->confirm_time = time();
                $row->save();

                $details = new \app\common\model\CompanyStocksDetails();
                $details->saveAll($data);

                $equip = new \app\common\model\Equip();
                $equip->saveAll($equipData);

                Tools::updateStocks(1,$row->company_id,$row->product_id,1,$data,"后台设备入库",1);

                //政策关系表录入
                $relationObj = Lib::getPolicyRelation(1,$row->company_id,$row->product_id,$row->policy_id);
                if(!$relationObj){
                    $relation = new PolicyRelation();
                    $relation->main_type = 1;
                    $relation->main_id = $row->company_id;
                    $relation->product_id = $row->product_id;
                    $relation->policy_id = $row->policy_id;
                    $relation->save();
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error($e->getMessage());

            }
        }elseif ($confirmType == 2){
            $row->confirm_type = $confirmType;
            $row->confirm_content = $confirmContent;
            $row->confirm_time = time();
            $row->save();
        }

        $this->success("接收成功！");
    }

    public function detail($ids){
        $row = $this->model->get($ids);

        $list = [];
        if($row->confirm_type == 1){
            $data = Lib::getStocksDetails($row->id);
            foreach ($data as $key => $val){
                $list[] = ["sn" => $val['sn']];
            }
        }else{
            if($row->add_type == 1){
                $fileData = Tools::importExcel($row->file_url);
                for($i = 1;$i < count($fileData);$i++){
                    $list[] = [
                        "sn" => $fileData[$i][0]
                    ];
                }
            }elseif ($row->add_type == 2){
                $list[] = [
                    "sn" => $row->sn
                ];
            }
        }
        $this->view->assign("row", $list);
        return $this->view->fetch();
    }

    public function policyList(){
        $productId = $this->request->post("id");
        if($this->auth->isSuperAdmin()){
            $type = 0;
            $id = 0;
        }else{
            $type = 1;
            $id = $this->auth->getCompany()->id;
        }
        $list = Lib::getPolicyByProduct($type,$id,$productId);
        $this->success("","",$list);
    }
}
